﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Hzexe.Wechat.SharpSDK.Message.JSONData.Support
{
    /// <summary>
    /// 下载媒体文件策略的委托
    /// </summary>
    /// <param name="media_id">媒体文件编号对应文档中的media_id</param>
    /// <returns></returns>
    public delegate MediaSolution MediaFileBeforeDownloadHandle(string media_id );

    /// <summary>
    /// 媒体数据
    /// </summary>
    public class MediaResult : ResultBase
    {
        public string contentType { get; set; }
        public string contentdisposition { get; set; }

        public MediaResult(MediaFileBeforeDownloadHandle method,string url)
        { 
            MediaSolution mediasol=null;
            if (null == method)
            {
                mediasol = new MediaSolution() { isSave = false };
            }
            else
            {
               var mc= System.Text.RegularExpressions.Regex.Match(url, "media_id=(.*?)(&|$)");
               if (!mc.Success)
                   throw new ArgumentException("URL不规范,不存在media_id参数");
                mediasol = method.Invoke(mc.Groups[1].Value);
            }

            var wc = new WebClient();
            try
            {
                var data = wc.DownloadData(url);
                contentType = wc.ResponseHeaders.AllKeys.Contains("Content-Type") ? wc.ResponseHeaders[HttpResponseHeader.ContentType] : "";
                contentdisposition = wc.ResponseHeaders.AllKeys.Contains("Content-disposition") ? wc.ResponseHeaders["Content-disposition"] : "";

                if (mediasol.isSave && mediasol.sw != null)
                {
                    mediasol.sw.Write(data);
                }
            }
            finally
            {
                wc.Dispose();
            }
        }
    }

    /// <summary>
    /// 媒体处理策略
    /// </summary>
    public class MediaSolution{
        [System.ComponentModel.DefaultValue(false )]
        public bool isSave{get;set;}
        public System.IO.StreamWriter sw{get;set;}
    }
}
